package top.lingkang.acgv.config.auth.handler;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import top.lingkang.acgv.acr.dto.ResponseResult;

@Component
public class ExceptionTranslatorHandler implements WebResponseExceptionTranslator {
    MultiValueMap headers = new HttpHeaders();

    public ExceptionTranslatorHandler() {
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.set("Content-Type", "application/json");
    }

    public ResponseEntity translate(Exception e) throws Exception {
        ResponseResult result = new ResponseResult();
        result.setCode(4);
        if (e instanceof InvalidGrantException) {
            result.setMessage("账号或密码错误：" + e.getMessage());
        } else if (e instanceof InsufficientAuthenticationException) {
            result.setMessage("无效的token，需要完整的身份验证：" + e.getMessage());
        } else if (e instanceof InternalAuthenticationServiceException) {
            result.setMessage("账号或密码错误！" );
        } else {
            result.setMessage(e.getMessage());
        }
        ResponseEntity entity = new ResponseEntity(JSONObject.toJSONString(result), headers, HttpStatus.OK);
        return entity;
    }
}
